package com.atdel.demo12;


/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo12
 * @Author: Del
 * @CreateTime: 2025-03-11  19:47
 * @Description: 使用实现Runnable接口方式实现卖票功能
 * @Version: 1.0
 */
public class MovieTicketSaleRunnableThread implements Runnable {

    //  电影票数，使用volatile确保可见性
    private volatile int  ticket = 50;

    public boolean saleTicket() {
        synchronized (this) {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket-- + "张票");
                return true;
            } else {
                System.out.println("票卖完了");
                return false;
            }
        }
    }

    @Override
    public void run() {
        while (saleTicket()) {
            if (ticket <= 0) {
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
